#!/bin/bash

export FOTA_VERSION_PROFILE="china"
# all: management and version; m: management; v: version
export FOTA_START_ITEMS="all"
while getopts ":p:s:" opt
do
  case $opt in
    s)
      FOTA_START_ITEMS=$OPTARG;;
    p)
      FOTA_VERSION_PROFILE=$OPTARG;;
    ?)
    echo "Unknown parameter"
    exit 1;;
  esac
done

stop() {
  # 进程数量
  # shellcheck disable=SC2086
  # shellcheck disable=SC2006
  prog_num=$(ps -ef | grep $1 | grep -v grep | wc -l)
  if [ "$prog_num" -eq 0 ]; then
    echo "$1 is stopped"
    return
  fi

  # 查出所有进程 id
  # shellcheck disable=SC2006
  prog_ids=$(ps -ef | grep $1 | grep -v grep | awk '{print $2}')

  for pid in $prog_ids; do
    kill -9 "$pid"
  done
  echo "stop $1 finish!"
}

echo "stop all java process and nginx process..."
stop java
stop nginx

curPath=$(dirname $(readlink -f "$0"))
echo "current path is $curPath"

if [ "${FOTA_START_ITEMS}" != "v" ]; then
  cd management-server
  echo "start management-server!!!"
  nohup java -jar $curPath/management-server/fota-manager-server-1.0.0-SNAPSHOT.jar >/dev/null 2>/dev/null &
  cd ..
fi

if [ "${FOTA_START_ITEMS}" != "m" ]; then
  cd version-server
  echo "start version-server!!!"
  if [ "${FOTA_VERSION_PROFILE}" != "" ]; then
    nohup java -jar -Dspring.profiles.active="${FOTA_VERSION_PROFILE}" $curPath/version-server/fota-version-server-1.0.0-SNAPSHOT.jar >/dev/null 2>/dev/null &
  else
    nohup java -jar $curPath/version-server/fota-version-server-1.0.0-SNAPSHOT.jar >/dev/null 2>/dev/null &
  fi
  cd ..
fi

if [ "${FOTA_START_ITEMS}" = "all" ]; then
  echo "start nginx with nginx.conf"
  nginx -c $curPath/nginx/nginx.conf
elif [ "${FOTA_START_ITEMS}" = "m" ]; then
  echo "start nginx with nginx-only-management.conf"
  nginx -c $curPath/nginx/nginx-only-management.conf
elif [ "${FOTA_START_ITEMS}" = "v" ]; then
  echo "start nginx with nginx-only-version-${FOTA_VERSION_PROFILE}.conf"
  nginx -c $curPath/nginx/nginx-only-version-"${FOTA_VERSION_PROFILE}".conf
fi

echo "start success！！！"
